package com.razorfish.configuration.condition 
{
	/**
	 * ...
	 * @author derek
	 */
	public class Operator 
	{
		private static const OP_NumberEquals:String = "==";
		private static const OP_NumberNotEquals:String = "!=";
		private static const OP_GreaterThan:String = ">";
		private static const OP_GreaterThanOrEquals:String = ">=";
		private static const OP_LessThan:String = "<";
		private static const OP_LessThanOrEquals:String = "<=";
		private static const OP_BeginsWith:String = "beginswith";
		private static const OP_EndsWith:String = "endswith";
		private static const OP_Contains:String = "contains";
		
		private static var _operatorList:Array = 
		[
			OP_NumberEquals,
			OP_NumberNotEquals,
			OP_GreaterThan,
			OP_GreaterThanOrEquals,
			OP_LessThan,
			OP_LessThanOrEquals,
			OP_BeginsWith,
			OP_EndsWith,
			OP_Contains
		];
		
		public static function isValid(operator:String):Boolean
		{
			if (operator == null) return false;
			return _operatorList.indexOf(operator.toLowerCase()) > -1;
		}
		
		public static function caculate(left:String, op:String, right:String):Boolean
		{
			if (left == null || right == null) return false;
			
			switch(op.toLowerCase())
			{
				case OP_NumberEquals:
					return left == right;
				case OP_NumberNotEquals:
					return left != right;
				case OP_GreaterThan:
					return parseFloat(left) > parseFloat(right);
				case OP_GreaterThanOrEquals:
					return parseFloat(left) >= parseFloat(right);
				case OP_LessThan:
					return parseFloat(left) < parseFloat(right);
				case OP_LessThanOrEquals:
					return parseFloat(left) <= parseFloat(right);
				case OP_BeginsWith:
					return left.indexOf(right) == 0;
				case OP_EndsWith:
					return (left.length > right.length) && (left.lastIndexOf(right) == left.length - right.length);
				case OP_Contains:
					return left.indexOf(right) > -1;
				default:
					throw new Error("Invalid operator");
			}
		}
	}
}
